﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace JWTToken授权验证
{
    /// <summary>
    /// Token服务实现
    /// </summary>
    public sealed class JWTService : IJWTService
    {
        private readonly IOptionsMonitor<JWTTokenOption> _option;

        /// <summary>
        /// 实例化
        /// </summary>
        /// <param name="option"></param>
        public JWTService(IOptionsMonitor<JWTTokenOption> option)
        {
            _option = option;
        }

        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public string GetToken(string userName, string password)
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.Name,userName),
                new Claim("NickName",userName),
                new Claim(ClaimTypes.Role,"Administrator"),
                new Claim("Password",password)
            };

            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_option.CurrentValue.SecurityKey!));

            SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: _option.CurrentValue.Issuer,
                audience: _option.CurrentValue.Audience,
                claims: claims,
                expires: DateTime.Now.AddMinutes(5),
                signingCredentials: signingCredentials
                );

            string returnToken = new JwtSecurityTokenHandler().WriteToken(token);

            return returnToken;

        }
    }
}